﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using IAC_2013.com.iac.util;
using System.Windows.Forms;

namespace IAC_2013.com.iac.util
{
    class CommonUtils
    {
        static SqlConnection conn = new SqlConnection(DBUtils.CONNECTION_STRING);
        static SqlCommand cmd;
        static SqlDataReader reader;
        static SqlDataAdapter da;
        static AutoCompleteStringCollection namesCollections;
        /*
         * ham kiem tra Ma
         */
        public static Boolean checkCode(String code, String codeNew, String sqlColumnName, String dbTable, String events)
        {
            String sql = "SELECT * FROM " + dbTable + " as tb WHERE tb." + sqlColumnName + " = '" + codeNew + "'";

            cmd = new SqlCommand(sql, conn);
            conn.Open();

            reader = cmd.ExecuteReader();
            int count = 0;
            while (reader.Read())
            {
                count++;
            }
            if (events.Trim().Equals("add") && count > 0)
            {
                conn.Close();
                return false;
            }
            else if (events.Trim().Equals("edit") && (!code.Trim().Equals(codeNew)) && count >=1 )
            {
                conn.Close();
                return false;
            }
            else
            {
                conn.Close();
                return true;
            }
            
        }

        public static AutoCompleteStringCollection autoCompleted(String tableName, String columnName)
        {
            namesCollections = new AutoCompleteStringCollection();
            String sql = "SELECT DISTINCT ["+ columnName +"] FROM ["+ tableName +"] ORDER BY ["+ columnName +"] ASC";
            cmd = new SqlCommand(sql, conn);
            conn.Open();
            reader = cmd.ExecuteReader();
            if (reader.HasRows == true)
            {
                while (reader.Read())
                {
                    namesCollections.Add(reader["" + columnName + ""].ToString());
                }
            }
            reader.Close();
            conn.Close();
            return namesCollections;
        }
    }
}
